<?php


namespace App\Services;

use Illuminate\Support\Facades\DB;
use App\Models\BreedConsume;
use App\Models\BreedUserCoin;
use App\Models\YhOrder;
use App\Models\Store;
use App\Models\LoveMember;
use App\Models\LoveRecords;
use App\Models\BreedCoinFlow;
use App\Models\CashierOrder;
use App\Models\BreedUserCoinQuota;
use App\Models\BreedCoinQuotaFlow;
use App\Models\HhmCoinCorpQuota;
use App\Models\HhmCoinCorpQuotaFlows;
class OrderPayService
{
    protected $valueType;

    

    /**
     * OrderPayService constructor.
     *
     * @param string $valueType usable|froze
     */
    public function __construct($valueType = '')
    {
    }

 

    /**
     * 消费抵扣沐浴露
     * @param array $data
     * @return string
     */
    public function deductionMYL(array $data)
    {
        //先查出设置的支持哪种沐浴露
        DB::transaction(function ()use($data) {
            $breedConsumes = BreedConsume::where(['is_swap'=>1])->orderBy('pay_sort')->get();
            $order_sn = $data['relation'];
            $order = YhOrder::where('order_sn', $order_sn)->first();
            $store_id = $order->store_id;
            $member_id = $data['member_id'];
            $store = Store::where('id',$store_id)->first();
            $store_name = $store->store_name;
            if (!isset($data['change_value']) || $data['change_value'] < 0) {
                return '变动值必须是正数';
            }
            $change_value = $data['change_value'];
            $coin_flow_remark = config('constants.coin_flow_remark');
            $userId = $data['member_id'];
            //按顺序扣减
            foreach($breedConsumes as $breedConsume){
                $record = BreedUserCoin::where(['user_id'=>$member_id,'consume_type'=>$breedConsume->id])->first();
                $num = $record->num;
                if($record){
                    if($num>$change_value){
                        $record->num = $num - $change_value;
                        $old_coin = $num;
                        $new_coin = $num - $change_value;
                        $record->save();
                        BreedCoinFlow::create(
                            ["uniacid"=>1, 
                            'send_user' => $userId,
                            'rec_user'=>0,
                            'num'=>$change_value,
                            'type'=>13,
                            'consume_type'=>$breedConsume->id,
                            'old_coin'=>$old_coin,
                            'new_coin'=>$new_coin,
                            'remark'=>$coin_flow_remark[13].$store_name,
                            'created_at'=>time(),
                            'updated_at'=>time(),
                            ]
                        );
                        break;
                    }else{
                        $change_value = $change_value - $num;
                        $old_coin = $record->num;
                        $record->num = 0;
                        $record->save();
                        BreedCoinFlow::create(
                            ["uniacid"=>1, 
                            'send_user' => 0,
                            'rec_user'=>$userId,
                            'num'=>$old_coin,
                            'type'=>13,
                            'consume_type'=>$breedConsume->id,
                            'old_coin'=>$old_coin,
                            'new_coin'=>0,
                            'remark'=>$coin_flow_remark[13].$store_name,
                            'created_at'=>time(),
                            'updated_at'=>time(),
                            ]
                        );
                    }
                }
            }
        });
        return true;
    }

    /**
     * 消费抵扣茶包
     * @param array $data
     * @return bool
     */
    public function deductionCB(array $data)
    {
        try {
            $uid = $data['member_id'];
            $change_value = $data['change_value'];
            
            // 查询用户茶包账户
            $memberLove = LoveMember::where('member_id', $uid)->first();
            
            if (!$memberLove) {
                \Log::error('[OrderPayService] 茶包账户不存在', ['member_id' => $uid]);
                return false;
            }
            
            // 检查余额是否充足
            if ($memberLove->usable < $change_value) {
                \Log::error('[OrderPayService] 茶包余额不足', [
                    'member_id' => $uid,
                    'usable' => $memberLove->usable,
                    'required' => $change_value
                ]);
                return false;
            }
            
            // 开始事务
            DB::beginTransaction();
            
            $old_value = $memberLove->usable;
            $usable = $memberLove->usable - $change_value;
            $new_value = $usable;
            
            // 更新茶包余额
            LoveMember::where('member_id', $uid)->update(['usable' => $usable]);
            
            // 创建流水记录
            LoveRecords::create([
                'uniacid' => 1,
                'member_id' => $uid,
                'old_value' => $old_value,
                'change_value' => '-'.$change_value,
                'new_value' => $new_value,
                'value_type' => 1,
                'type' => 2,
                'source' => 18,
                'relation' => $data['relation'],
                'operator' => 2,
                'operator_id' => 0,
                'remark' => '订单支付',
            ]);
            
            DB::commit();
            return true;
            
        } catch (\Exception $e) {
            DB::rollBack();
            
            \Log::error('[OrderPayService] 茶包扣除失败', [
                'error' => $e->getMessage(),
                'member_id' => $data['member_id'] ?? null
            ]);
            
            return false;
        }
    }

     /**
     * 消费抵扣额度
     * @param array $data
     * @return bool
     */
    public function deductionQuota(array $data){
        try {
            $uid = $data['member_id'];
            $change_value = $data['change_value'];
            
            // 查询用户额度账户
            $CoinQuota = BreedUserCoinQuota::where('user_id',$uid)->first();
            $CoinQuota_num =  $CoinQuota->num;  //个人额度
            $CorpQuota_stock_num = 0;//云仓额度
            $store = Store::where('uid',$uid)->first();
            if($store){
                $CoinCorpQuota = HhmCoinCorpQuota::where('store_id',$store->id)
                ->where('status',2)
                ->where('stock_status',0)
                ->first();
                $CorpQuota_stock_num = $CoinCorpQuota->stock_num ?? 0;
            }
            // 检查余额是否充足
            if ($CoinQuota_num +$CorpQuota_stock_num < $change_value) {
                \Log::error('[OrderPayService] 额度余额不足', [
                    'member_id' => $uid,
                    'num' => $CoinQuota->num,
                    'required' => $change_value
                ]);
                return false;
            }
            $order_sn = $data['relation'];
            $order = YhOrder::where('order_sn', $order_sn)->first();
            $store_id = $order->store_id;
            $store = Store::where('id',$store_id)->first();
            $store_name = $store->store_name;
            // 开始事务
            DB::beginTransaction();
            if($CoinQuota_num>=$change_value){
                $old_value = $CoinQuota_num;
                $num = $change_value;
                $new_value = $CoinQuota_num - $change_value;
                // 更新额度余额
                BreedUserCoinQuota::where('user_id', $uid)->update(['num' => $new_value]);
                // 创建流水记录
                BreedCoinQuotaFlow::create([
                    "uniacid"=>1, 
                    'send_user' => 0,
                    'rec_user'=>$uid,
                    'num'=>$num,
                    'type'=>5,
                    'old_coin'=>$old_value,
                    'new_coin'=>$new_value,
                    'remark'=>'['.$store_name.']'.'商品订单消费，订单号:'.$order_sn,
                    'created_at'=>time(),
                    'updated_at'=>time(),
                ]);
            }else{
                $old_value = $CoinQuota_num;
                $num = $CoinQuota_num;
                $new_value = 0;
                // 更新额度余额
                BreedUserCoinQuota::where('user_id', $uid)->update(['num' => $new_value]);
                // 创建流水记录
                BreedCoinQuotaFlow::create([
                    "uniacid"=>1, 
                    'send_user' => 0,
                    'rec_user'=>$uid,
                    'num'=>$num,
                    'type'=>5,
                    'old_coin'=>$old_value,
                    'new_coin'=>$new_value,
                    'remark'=>'['.$store_name.']'.'商品订单消费，订单号:'.$order_sn,
                    'created_at'=>time(),
                    'updated_at'=>time(),
                ]);
                //剩下的扣云仓库存额度
                $change_value = $change_value - $CoinQuota_num;
                
                $old_value = $CorpQuota_stock_num;
                $num = $change_value;
                $new_value = $CorpQuota_stock_num - $change_value;
                // 更新额度余额
                HhmCoinCorpQuota::where('store_id', $store->id)->update(['stock_num' => $new_value]);
                 // 创建流水记录
                HhmCoinCorpQuotaFlows::create([
                    "uniacid"=>1, 
                    'send_user' => 0,
                    'rec_user'=>$uid,
                    'num'=>$num,
                    'type'=>5,
                    'old_coin'=>$old_value,
                    'new_coin'=>$new_value,
                    'remark'=>'['.$store_name.']'.'商品订单消费，订单号:'.$order_sn,
                    'created_at'=>time(),
                    'updated_at'=>time(),
                ]);
            }
            
            
            DB::commit();
            return true;
            
        } catch (\Exception $e) {
            DB::rollBack();
            
            \Log::error('[OrderPayService] 额度扣除失败', [
                'error' => $e->getMessage(),
                'member_id' => $data['member_id'] ?? null
            ]);
            
            return false;
        }
    }


   /**
     * 
     * @param array $data
     * @return string
     */
    public function sendUserCoin(array $data)
    {

          DB::transaction(function ()use($data) {
            $order = YhOrder::where('id', $data['order_id'])->first();
            $orderId = $data['order_id'];
            $userId = $data['user_id'];
            $price = $order->price;
            $settlement_num = $data['settlement_num'];
            $settlement_type = $data['out_type_attribute'];
            $usercoin = $price * $settlement_num/100;
            $rece_user = BreedUserCoin::where(['user_id'=>$userId,'consume_type'=>$settlement_type])->first();
            $old_coin = 0;
            $new_coin = 0;
            if($rece_user){
                $rece_user_num = $rece_user->num;
                $rece_user->num = $rece_user_num + $usercoin;
                $old_coin = $rece_user_num;
                $new_coin = $rece_user_num + $usercoin;
                $rece_user->save();
            }else{
                $record = new BreedUserCoin(
                ["uniacid"=>1, 'user_id' => $userId,'consume_type'=>$settlement_type,'num'=>$usercoin]
                );
                $new_coin = $usercoin;
                $record->save();
            }
            $coin_flow_remark = config('constants.coin_flow_remark');
            BreedCoinFlow::create(
                ["uniacid"=>1, 
                'send_user' => 0,
                'rec_user'=>$userId,
                'num'=>$usercoin,
                'type'=>19,
                'consume_type'=>$settlement_type,
                'old_coin'=>$old_coin,
                'new_coin'=>$new_coin,
                'remark'=>$coin_flow_remark[19].$order->order_sn,
                'created_at'=>time(),
                'updated_at'=>time(),
                ]
            );
            //修改订单状态
            // $order->update(['pay_type_id'=>$data['pay_type_id'],'status' => 1,'pay_time'=>time(),'send_time'=>time(),'dispatch_type_id'=>8]);
            //修改结算状态
            // $cashierOrder = CashierOrder::where('order_id',$orderId)->first();
            // if($cashierOrder){
            //     $cashierOrder->has_withdraw = 1;
            //     $cashierOrder->has_settlement = 1;
            //     $cashierOrder->fee_percentage = 100-$settlement_num;
            //     $cashierOrder->fee = $price - $usercoin;
            //     $cashierOrder->settle_time = '1650872407';
            //     $cashierOrder->amount = 0;
            //     $cashierOrder->pay_type_id = $data['pay_type_id'];
            //     $cashierOrder->save();
            // }
            // $storeOrder = StoreOrder::where('order_id',$orderId)->first();
            // if($storeOrder){
            //     $storeOrder->has_withdraw = 1;
            //     $storeOrder->has_settlement = 1;
            //     $storeOrder->fee_percentage = 100-$settlement_num;
            //     $storeOrder->fee = $price - $usercoin;
            //     $storeOrder->settle_time = '1650872407';
            //     $storeOrder->amount = 0;
            //     $storeOrder->pay_type_id = $data['pay_type_id'];
            //     $storeOrder->save();
            // }

        });
        return true;
    }

}
